
var mqtt = require('mqtt');
const MysqlPool = require ('./mysql_pool.js');
var fs = require('fs');
var tmpbitmap = '';

global.machineshipments = [];

const mqtt_MysqlPool = new MysqlPool();

var options = {
//mqtt客户端的id，这里面应该还可以加上其他参数，具体看官方文档
  clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
  //username:'admin',
  //password:'112233',   
}   

var mqttclient = mqtt.connect("ws://mq.tongxinmao.com:18832/mqtt",options)

function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    //var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file

    fs.open(file, 'w', function( e, id ) {
      fs.write( id, base64str,'binary',function(){
        fs.close(id, function(){
          console.log('file closed');
        });
      });
    });
}

function stringToBase64(str){
    var base64Str = new Buffer(str).toString('base64');
    return base64Str;
}
function base64ToString(base64Str){
    var str = new Buffer(base64Str,'base64').toString();
    return str;
}

//建立连接
mqttclient.on('connect', function () {
	console.log("中心服务器连接成功!")

    var subscribes = ['super/machine/goline',
                      'super/machine/offline',
                      'home/photo/'];
    //订阅主题 presence
    mqttclient.subscribe(subscribes, function (err) {
      if (!err) {
        console.log("中心服务器消息订阅成功!")
      }else{
      //打印错误
        console.log(err)
      }
    })

    subscribes = ['super/machine/shipment/return'];   
       
    mqttclient.subscribe(subscribes, {qos:2},function (err) {
      if (!err) {
        console.log("中心服务器qos2消息订阅成功!")
      }else{
      //打印错误
        console.log(err)
      }
    })  
})

//如果连接错误，打印错误
mqttclient.on('error', function (err) {
	console.log(err)
	mqttclient.end()
})

//如果client订阅主题成功，那么这里就是当接收到自己订阅主题的处理逻辑
mqttclient.on('message', function (topic, message) {
// message is Buffer,此处就是打印消息的具体内容
  var msg = message.toString();
  var topicstr = topic.toString();

  if(topicstr == 'home/photo/') {   
    tmpbitmap = tmpbitmap + msg;	
    console.log(tmpbitmap);	
    return 
  }

  //console.log(topicstr+":"+msg);

  try{ 
   var params = JSON.parse( msg );

   if(topicstr == 'super/machine/goline') {
     	 var querystr = "update yzn_machine set runningstate=1 where id="+params.machineid+" and userid="+params.playerid;

    	 mqtt_MysqlPool.query(querystr,function(err,vals,fields){
    	  if(err) {
    	   throw err;
    	  }else{
    	   //console.log( vals );
    	  }
    	 });
   }
   else if(topicstr == 'super/machine/offline') {
     	 var querystr = "update yzn_machine set runningstate=0 where id="+params.machineid+" and userid="+params.playerid;
    	 mqtt_MysqlPool.query(querystr,function(err,vals,fields){
    	  if(err) {
    	   throw err;
    	  }else{
    	   //console.log( vals );
    	  }
    	 });
   }
   else if(topicstr == 'super/machine/shipment/return') {
      if(params.state == 1) {
         global.machineshipments[params.machine_id] = 0;

         //var querystr = "update yzn_pay_account set shipment="+params.state+" where id="+params.orderid+" and machineid="+params.machine_id;
         var querystr = "call goods_shipment("+params.orderid+","+params.machine_id+","+params.state+");";

         mqtt_MysqlPool.query(querystr,function(err,vals,fields){
          if(err) {
           throw err;
          }else{
            //给所在机子发送出货成功消息
            var qtt = {}; //定义消息（可以为字符串，对象等）
            qtt.machine_id = params.machine_id;
            qtt.playerid = params.playerid;
            qtt.cargoway = params.cargoway;
            qtt.paymentcode = params.paymentcode;
            qtt.orderid = params.orderid;
            qtt.state = params.state;

            mqttclient.publish('super/machine/shipment/return/'+params.machine_id,JSON.stringify(qttstr),{ qos: 0, retain: false })
          }
         });
      }
      else {
        // 如果第一次出货不成功，就再出货一次
        global.machineshipments[params.machine_id] += 1;

        if(global.machineshipments[params.machine_id] <= 1) {
          var qtt = {}; //定义消息（可以为字符串，对象等）
          qtt.machine_id = params.machine_id;
          qtt.playerid = params.playerid;
          qtt.cargoway = params.cargoway;
          qtt.paymentcode = params.paymentcode;
          qtt.orderid = params.orderid;

          mqttclient.publish('super/machine/shipment',JSON.stringify(qttstr),{ qos: 2, retain: false })
        }
      }
   }

  }catch(exception){
   console.info(exception.message);
  } 
})
